package com.sskj.level.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.BuySellEnum;
import com.sskj.level.bean.TradeListBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.HolderFragmentPresenter;
import com.sskj.level.util.CoinUtil;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.AppVersionBean;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.LevelCoinType;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * 持仓
 */
@Route(path = RConfig.LEVEL_FRAGMENT_HOLDER)
public class HolderFragment extends BaseFragment<HolderFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R2.id.level_all_pc)
    TextView levelAllPc;
    private SlimAdapter<TradeListBean> slimAdapter;
    private int curPos;
    private MVCCoolHelper<List<TradeListBean>> mvcCoolHelper;
    private MaterialDialog setTip;
    private Disposable subscribe;
    @Inject
    UserViewModel userViewModel;
    @Autowired
    String stockCode;
    private Disposable changePriceDispo;
    private MaterialDialog allTip;
    private UserData userData;

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_holder;
    }

    @Override
    public HolderFragmentPresenter getPresenter() {
        return new HolderFragmentPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden && mvcCoolHelper != null) {
            mvcCoolHelper.refresh();
        }
        super.onHiddenChanged(hidden);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        ARouter.getInstance().inject(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        slimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_holder, new SlimInjector<TradeListBean>() {
            @Override
            public void onInject(TradeListBean data, IViewInjector injector, List payloads) {
                injector
                        .textColor(R.id.tv_mm, ContextCompat.getColor(App.INSTANCE, BuySellEnum.getByType(data.getBuyBillType()).getColorRes()))
                        .text(R.id.tv_mm, BuySellEnum.getByType(data.getBuyBillType()).getTitle())//买入卖出
                        .text(R.id.tv_bz, data.getStockCode().toUpperCase())//币种类型
                        .text(R.id.tvType, data.getMarketLimit())//市价限价
                        .text(R.id.tv_time, data.getCreateTime())//时间
                        .text(R.id.tvLevel, data.getStockLever())//杠杆
                        .text(R.id.tvFee, CoinUtil.keepUSDT(data.getBuyDealFee()))//手续费
                        .text(R.id.tvHoldPrice, data.getBuyPrice())//持仓价
                        .text(R.id.tvNewPrice, data.getNewPrice())//最新价
                        .text(R.id.tvNum, data.getCountUsable())//数量
                        .text(R.id.tvNightFee, data.getOvernightFee())//过夜费
                        .text(R.id.tvEnsureMoney, data.getBuyMarginFee())//保证金
                        .text(R.id.tvWinPrice, data.getStopProfitPrice())//止盈价
                        .text(R.id.tvLossPrice, data.getStopLossPrice())//止损价
                        .text(R.id.level_fd_type, App.INSTANCE.getString(R.string.levelholderFragment1) + data.getWinLoseMoney())//盈亏
                        .background(R.id.level_fd_type, ContextCompat.getDrawable(App.INSTANCE, Double.valueOf(data.getWinLoseMoney()) > 0 ? R.drawable.level_shape_green : R.drawable.level_shape_red))

                        .clicked(R.id.tvPingCang, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            pingCang();
                        })
                        .clicked(R.id.tvSet, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            mPresenter.getSet(data.getStockCode());
                        });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<TradeListBean> dataSource = new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<TradeListBean>)
                page -> mPresenter.getTradeListFlow(page + "", "1000000", stockCode, userData), 1000000);

        mvcCoolHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcCoolHelper.setDataSource(dataSource);
        mvcCoolHelper.setAdapter(slimAdapter);
        ClickUtil.click(levelAllPc, () -> {
            allTip = TipUtil.getSureTip(getActivity(), App.INSTANCE.getString(R.string.leveltradeActivity5), () -> {
                allTip.dismiss();
                mPresenter.levelAllPc(null);
            });
            allTip.show();
        });
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
            mvcCoolHelper.refresh();
        });

        startTimer();
    }


    public void updateUI(List<TradeListBean> data) {

        if (data == null || data.size() == 0) {
            LiveDataBus.get().with(RxBusCode.ALL_PINGCANG_DISMISS).postValue(1);
        } else {
            LiveDataBus.get().with(RxBusCode.ALL_PINGCANG_SHOW).postValue(1);
        }
        if (slimAdapter != null) {
            if (data.size() > 0 && slimAdapter.getData().size() == 0 || data.size() == 0 && slimAdapter.getData().size() > 0) {
                mvcCoolHelper.refresh();
            } else if (data.size() > 0 && slimAdapter.getData().size() > 0) {
                slimAdapter.updateData(data);
            } else if (data.size() == 0 && slimAdapter.getData().size() == 0) {

            }
        }
    }

    public void refresh(LevelCoinType coinType) {
        stockCode = coinType.getCode();
        if (mvcCoolHelper != null) {
            mvcCoolHelper.refresh();
        }
//        mPresenter.getTradeList(1 + "", "1000000", stockCode, userData);
    }

    public void refresh() {
        if (mvcCoolHelper != null) {
            mvcCoolHelper.refresh();
        }
    }

    /**
     * 平仓
     */
    private void pingCang() {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        boolean isBuy = dataItem.getBuyBillType().equals(BuySellEnum.BUY.getType());
        TipLevelUtil.getPingcangTip(getActivity(), isBuy,
                dataItem.getNewPrice(), dataItem.getCountUsable(), (num) -> mPresenter.pingCang(dataItem.getEntrustNo(), num));
    }

    /**
     * 设置点位
     */
    public void setStop(String stopWin, String stopLoss) {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        setTip = TipLevelUtil.showTradeSet(getActivity(),
                dataItem.getStockCode(),
                dataItem.getBuyBillType(),
                dataItem.getNewPrice(),
                stopWin,
                stopLoss,
                CoinUtil.keepCoinPrice(dataItem.getStockCode(), dataItem.getStopProfitPrice()),
                CoinUtil.keepCoinPrice(dataItem.getStockCode(), dataItem.getStopLossPrice()),
                list -> {
                    mPresenter.setStop(dataItem.getEntrustNo() + "",
                            TextUtils.isEmpty(list.get(0)) ? "0" : list.get(0),
                            TextUtils.isEmpty(list.get(1)) ? "0" : list.get(1));
                }
        );
    }

    public void updateCoin(CoinBean coinBean) {
        if (slimAdapter != null && slimAdapter.getData() != null && !slimAdapter.getData().isEmpty()) {
            DisposUtil.close(changePriceDispo);
            changePriceDispo = Flowable.fromIterable(slimAdapter.getData())
                    .filter(tradeListBean -> tradeListBean.getStockCode().equalsIgnoreCase(coinBean.getCode()))
                    .filter(tradeListBean -> !tradeListBean.getNewPrice().equals(coinBean.getPrice()))
                    .subscribe(tradeListBean -> {
                        tradeListBean.setNewPrice(coinBean.getPrice());
                        slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(tradeListBean), 1);
                    }, e -> {
                    });
            if (setTip != null && setTip.isShowing() && curPos <= slimAdapter.getData().size() - 1) {
                if (coinBean.getCode().equalsIgnoreCase(slimAdapter.getDataItem(curPos).getStockCode())) {
                    TipLevelUtil.updatePrice(setTip, coinBean.getPrice());
                }
            }
        }

    }

    @Override
    protected void initData() {
        super.initData();
        LiveDataBus.get().with(RxBusCode.LEVEL_ALL_PC).observe(this, o -> updatePrice());
        LiveDataBus.get().with(RxBusCode.PUSH_COIN_BEAN_BIBI, CoinBean.class)
                .observe(this, this::updateCoin);
        if (stockCode != null) {
            levelAllPc.setVisibility(View.GONE);
            LiveDataBus.get().with(RxBusCode.LEVEL_FRESH)
                    .observe(this, o -> refresh());
            LiveDataBus.get().with(RxBusCode.LEVEL_CHANGE_COIN, LevelCoinType.class)
                    .observe(this, this::refresh);
        } else {
            LiveDataBus.get().with(RxBusCode.ALL_PINGCANG_DISMISS).observe(this, o -> hideAllPingcang());
            LiveDataBus.get().with(RxBusCode.ALL_PINGCANG_SHOW).observe(this, o -> showAllPingcang());
        }
    }

    public void hideAllPingcang() {
        if (levelAllPc != null) {
            levelAllPc.setVisibility(View.INVISIBLE);
        }
    }

    public void showAllPingcang() {
        if (levelAllPc != null && curPos == 0) {
            levelAllPc.setVisibility(View.VISIBLE);
        }
    }

    public void updatePrice() {
        refresh();
    }

    private void startTimer() {
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> {
                    mPresenter.getTradeList(1 + "", "1000000", stockCode, userData);
                });
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(changePriceDispo);
        DisposUtil.close(subscribe);
        super.onDestroy();
    }


    public void pingCangSuccess() {
        ToastUtil.showShort(App.INSTANCE.getString(R.string.level_pingcang_success));
        userViewModel.update();
        refresh();
    }

}
